"""
工作台页面

系统主页面，显示系统概览、快捷操作和最近活动
"""

import tkinter as tk
from tkinter import ttk, messagebox
from pathlib import Path
import sys
from datetime import datetime

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame, 
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class DashboardPage(BasePage):
    """工作台页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)

        # 欢迎页面内容
        self.create_welcome_content()
    
    def create_welcome_content(self):
        """创建欢迎页面内容"""
        # 主容器
        main_container = ttk.Frame(self.frame)
        main_container.pack(fill="both", expand=True, padx=DesignSystem.SPACING['xl'],
                           pady=DesignSystem.SPACING['xl'])

        # 1. 快速开始区域
        self.create_quick_start_section(main_container)

        # 2. 项目管理区域
        self.create_project_section(main_container)

        # 3. 项目列表区域
        self.create_project_list_section(main_container)
    
    def create_quick_start_section(self, parent):
        """创建科技感的快速开始区域"""
        # 创建渐变背景的主按钮容器
        gradient_frame = tk.Frame(
            parent,
            bg=DesignSystem.COLORS['primary'],
            relief='flat',
            bd=0,
            height=80
        )
        gradient_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        gradient_frame.pack_propagate(False)

        # 创建圆角效果的内容容器
        content_frame = tk.Frame(
            gradient_frame,
            bg=DesignSystem.COLORS['primary'],
            relief='flat',
            bd=0
        )
        content_frame.pack(fill="both", expand=True, padx=4, pady=4)

        # 主按钮 - 占整个宽度，科技感设计
        main_button = tk.Button(
            content_frame,
            text="🚀 开始混剪",
            font=(DesignSystem.FONTS['family_primary'], 16, 'bold'),
            bg=DesignSystem.COLORS['primary'],
            fg='white',
            activebackground=DesignSystem.COLORS['primary_hover'],
            activeforeground='white',
            relief='flat',
            bd=0,
            cursor='hand2',
            command=self.start_video_editing
        )
        main_button.pack(fill="both", expand=True)

        # 添加悬停效果
        def on_enter(e):
            main_button.config(bg=DesignSystem.COLORS['primary_hover'])

        def on_leave(e):
            main_button.config(bg=DesignSystem.COLORS['primary'])

        main_button.bind("<Enter>", on_enter)
        main_button.bind("<Leave>", on_leave)

    def create_project_section(self, parent):
        """创建项目管理区域"""
        # 项目管理容器
        project_container = ttk.Frame(parent)
        project_container.pack(fill="x", pady=(0, DesignSystem.SPACING['lg']))

        # 项目管理头部
        header_frame = ttk.Frame(project_container)
        header_frame.pack(fill="x", pady=DesignSystem.SPACING['md'])

        # 左侧：项目标题、数量和排序
        left_frame = ttk.Frame(header_frame)
        left_frame.pack(side="left", fill="x", expand=True)

        # 项目标题和数量
        title_label = ttk.Label(
            left_frame,
            text="📁 项目 (12)",
            style='Heading.TLabel'
        )
        title_label.pack(side="left")

        # 排序下拉框
        sort_frame = ttk.Frame(left_frame)
        sort_frame.pack(side="left", padx=(DesignSystem.SPACING['lg'], 0))

        sort_label = ttk.Label(sort_frame, text="排序:", style='Body.TLabel')
        sort_label.pack(side="left")

        sort_var = tk.StringVar(value="最新")
        sort_combo = ttk.Combobox(
            sort_frame,
            textvariable=sort_var,
            values=["最新", "最旧", "名称", "状态"],
            state="readonly",
            width=8
        )
        sort_combo.pack(side="left", padx=(DesignSystem.SPACING['xs'], 0))

        # 右侧：操作按钮
        right_frame = ttk.Frame(header_frame)
        right_frame.pack(side="right")

        # 圆角搜索框容器
        search_container = tk.Frame(
            right_frame,
            bg=DesignSystem.COLORS['bg_card'],
            relief='flat',
            bd=1,
            highlightbackground=DesignSystem.COLORS['border_light'],
            highlightthickness=1
        )
        search_container.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))

        # 搜索图标
        search_icon = ttk.Label(
            search_container,
            text="🔍",
            style='Body.TLabel'
        )
        search_icon.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))

        # 搜索输入框
        search_entry = tk.Entry(
            search_container,
            bg=DesignSystem.COLORS['bg_card'],
            fg=DesignSystem.COLORS['text_primary'],
            relief='flat',
            bd=0,
            width=15,
            font=DesignSystem.FONTS['body']
        )
        search_entry.pack(side="left", padx=(0, DesignSystem.SPACING['sm']), pady=4)
        search_entry.insert(0, "搜索项目...")

        # 搜索框焦点事件
        def on_search_focus_in(e):
            if search_entry.get() == "搜索项目...":
                search_entry.delete(0, tk.END)
                search_entry.config(fg=DesignSystem.COLORS['text_primary'])

        def on_search_focus_out(e):
            if search_entry.get() == "":
                search_entry.insert(0, "搜索项目...")
                search_entry.config(fg=DesignSystem.COLORS['text_muted'])

        search_entry.bind("<FocusIn>", on_search_focus_in)
        search_entry.bind("<FocusOut>", on_search_focus_out)
        search_entry.config(fg=DesignSystem.COLORS['text_muted'])

        # 布局方式按钮
        layout_btn = ttk.Button(
            right_frame,
            text="⊞",
            width=3,
            style='Secondary.TButton'
        )
        layout_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))

        # 垃圾桶按钮
        trash_btn = ttk.Button(
            right_frame,
            text="🗑️",
            width=3,
            style='Danger.TButton'
        )
        trash_btn.pack(side="left")
    
    def create_project_list_section(self, parent):
        """创建项目列表区域"""
        # 项目列表卡片
        list_frame = create_card_frame(parent, "")
        list_frame.pack(fill="both", expand=True)

        # 项目列表容器
        list_container = ttk.Frame(list_frame)
        list_container.pack(fill="both", expand=True, pady=DesignSystem.SPACING['md'])

        # 创建项目网格 (3列)
        projects = [
            {"name": "时尚T恤宣传片", "date": "2024-01-15", "status": "已完成"},
            {"name": "运动鞋广告视频", "date": "2024-01-14", "status": "进行中"},
            {"name": "手提包展示视频", "date": "2024-01-13", "status": "已完成"},
            {"name": "面霜产品介绍", "date": "2024-01-12", "status": "草稿"},
            {"name": "口红试色视频", "date": "2024-01-11", "status": "已完成"},
            {"name": "护肤品套装", "date": "2024-01-10", "status": "进行中"},
        ]

        # 创建项目卡片网格
        for i, project in enumerate(projects):
            row = i // 3
            col = i % 3

            # 项目卡片
            project_card = ttk.Frame(
                list_container,
                relief="solid",
                borderwidth=1,
                padding=DesignSystem.SPACING['md']
            )
            project_card.grid(
                row=row, column=col,
                sticky="ew",
                padx=DesignSystem.SPACING['sm'],
                pady=DesignSystem.SPACING['sm']
            )

            # 项目名称
            name_label = ttk.Label(
                project_card,
                text=project["name"],
                style='Body.TLabel',
                font=(DesignSystem.FONTS['family_primary'], 12, 'bold')
            )
            name_label.pack(anchor="w")

            # 项目日期
            date_label = ttk.Label(
                project_card,
                text=project["date"],
                style='Muted.TLabel'
            )
            date_label.pack(anchor="w", pady=(DesignSystem.SPACING['xs'], 0))

            # 项目状态
            status_color = {
                "已完成": DesignSystem.COLORS['success'],
                "进行中": DesignSystem.COLORS['info'],
                "草稿": DesignSystem.COLORS['warning']
            }.get(project["status"], DesignSystem.COLORS['text_muted'])

            status_label = ttk.Label(
                project_card,
                text=f"● {project['status']}",
                foreground=status_color,
                style='Body.TLabel'
            )
            status_label.pack(anchor="w", pady=(DesignSystem.SPACING['xs'], 0))

        # 配置网格权重
        for i in range(3):
            list_container.grid_columnconfigure(i, weight=1)
    
    # 事件处理方法
    def start_video_editing(self):
        """开始混剪"""
        self.app.show_page("trigger_task")

    def create_new_project(self):
        """创建新项目"""
        self.app.show_page("trigger_task")

    def import_project(self):
        """导入项目"""
        self.app.show_page("add_material")
